package com.apache.security.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.apache.security.SecurityFilter;

public class SqlCookieFilter implements SecurityFilter {

	private Logger log = Logger.getLogger(SqlCookieFilter.class);
	private String inj_str = "select |insert |drop |union |delete |update |javascript|<script|script |"
			+ "alert(|<iframe|'and| and |<a href|<input|<img|<audio|onerror\\=";//过滤掉的sql关键字，可以手动添加

	private String errorPage;

	private String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
			+ "(\\b(select |update |delete |insert |trancate |into |substr |ascii |declare |exec |count |master |drop |execute )\\b)";

	private Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);

	public int doFilterInvoke(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException {
		//获得所有请求参数名  
		Enumeration params = request.getParameterNames();
		//		String sql = "";
		while (params.hasMoreElements()) { //得到参数名
			String name = params.nextElement().toString();
			String[] value = request.getParameterValues(name);
			for (int i = 0; i < value.length; i++) {
				boolean mark = isValidStr(value[i]);
				if (!mark) {
					response.sendRedirect(request.getContextPath() + "/" + errorPage);
					return FAILURE;
				}
			}
		}
		/*if (StrUtil.isNotNull(sql)) {
			log.info("当前请求参数:" + sql);
			if (sql_inj(sql.toLowerCase())) {
				response.sendRedirect(request.getContextPath() + "/" + errorPage);
				return FAILURE;
			}
		}*/
		return SUCCESS;
	}

	/*public boolean sql_inj(String str) {
		String[] badStrs = inj_str.split("\\|");
		for (int i = 0; i < badStrs.length; i++) {
			if (str.indexOf(badStrs[i]) >= 0) {
				return true;
			}
		}
		return false;
	}*/

	/*************************************************************************** 
	 * 参数校验 
	 *  
	 * @param str 
	 */
	private boolean isValidStr(String str) {
		str = java.net.URLDecoder.decode(str);
		if (sqlPattern.matcher(str).find()) {
			log.error("未能通过过滤器：p=" + str);
			return false;
		}
		return isValid(str);
	}

	private boolean isValid(String p) {
		p = p.toUpperCase();
		if (p.indexOf("<A HREF ") >= 0 || p.indexOf("DROP ") >= 0 || p.indexOf("EXECUTE") >= 0
				|| p.indexOf("EXEC") >= 0 || p.indexOf("TRUNCATE") >= 0 || p.indexOf("<SCRIPT ") >= 0
				|| p.indexOf("JAVASCRIPT") >= 0 || p.indexOf("ALERT(") >= 0 || p.indexOf("<INPUT ") >= 0
				|| p.indexOf("<IMG ") >= 0 || p.indexOf("<AUDIO ") >= 0) {
			log.error("未能通过过滤器：p=" + p);
			return false;
		}
		return true;
	}

	public void setErrorPage(String errorPage) {
		this.errorPage = errorPage;
	}

}
